<?php
//error_reporting(E_ALL);

echo '<form name="title" method="post" autocomplete="on">';
echo '<input type=text name="title" required/>';
echo '<br/><input type="submit" value="Submit"/>';
echo '<input type=hidden name="submitted" value="1"/>';
echo '</form>';

if ($_POST[submitted]==1)
{
	
	include 'functions.php';
	//error_reporting(E_ALL);
	//http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles=Main%20Page

	//starting information
	$rootTitle = $_POST[title];
	$rootTitle = stripslashes($rootTitle);

	//parse determiners from title and put them back at the front
	//The
	if (stripos($rootTitle, ', the')>=1)
	{
		$rootTitle = str_ireplace(', the', '', $rootTitle);
		$rootTitle = 'the '.$rootTitle;
	}
	//An
	if (stripos($rootTitle, ', an')>=1)
	{
		$rootTitle = str_ireplace(', an', '', $rootTitle);
		$rootTitle = 'an '.$rootTitle;
	}
	//A
	if (stripos($rootTitle, ', a')>=1)
	{
		$rootTitle = str_ireplace(', a', '', $rootTitle);
		$rootTitle = 'a '.$rootTitle;
	}

	//get type
	$type = 'Book';

	if ($type=='Book')
	{
		$searchType = ' (novel)';
	}
 
	//convert to url
	//capitalize per wikipedia guidelines
	$searchTitle = wiki_caps($rootTitle);
	//echo $searchTitle;
	$searchTitle = urlencode($searchTitle);

	//construct url
	$rooturl = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles';
	$completeurl = "$rooturl=$searchTitle&indexpageids&redirects&continue=";

	echo "Original search: <a target='_blank' href='$completeurl'>$completeurl</a></br>";

	$request = curl_build($completeurl);
	$result = json_decode($request,true);

	$missing = $result[query][pages]['-1'][missing];

	if (isset($missing))
	{
		$missing = 1;
		//echo $missing;
	}

	//first search is not returning results, rerun with initcaps
	if ($missing == 1)
	{
		//echo "<br/>No results - rerunning with initcaps<br/>";
		$missing = 0;
		$searchTitle = ucwords($rootTitle);
		$searchTitle = urlencode($searchTitle);
		//construct url
		$completeurl = "$rooturl=$searchTitle&indexpageids&redirects&continue=";
		echo "Initcaps: <a target='_blank' href='$completeurl'>$completeurl</a></br>";

		$request = curl_build($completeurl);

		$result = json_decode($request,true);

		$missing = $result[query][pages]['-1'][missing];
		if (isset($missing))
		{
			$missing = 1;
		}

	}

	//if second search is not returning results, try adding media type to search
	//e.g. novel, film, album

	$pageId = $result[query][pageids][0];//get page id from article info
	$result2 = $result[query][pages][$pageId];//get actual article text
	$titleP = $result2[title];

	$result3 = $result2[revisions][0]['*'];
	$results4 = explode('{{', $result3);
	$results4 = str_ireplace('}}', '', $results4);

	//find infobox
	$infoBox = preg_grep('/(?i)Infobox/', $results4);
	$infoBox = array_values($infoBox);//reindex
	$infoBox = $infoBox[0];//get only first infobox if there are multiples
	$infoBoxA[] = $infoBox;//create array
	$infoBoxA = array_filter($infoBoxA);//remove empty array elements
	$infoBoxA = preg_replace('/\s\s+/', ' ', $infoBoxA);//replace multiple spaces with one


	if (is_array($infoBoxA)&&count($infoBoxA)==0)//no infobox
		{
		//convert to url
		//capitalize per wikipedia guidelines
		$searchTitle = wiki_caps($rootTitle);
		$searchTitle .= $searchType;//redo search with type
		$searchTitle = urlencode($searchTitle);
		//construct url
		$completeurl = "$rooturl=$searchTitle&indexpageids&redirects&continue=";
		echo "No Infobox: <a target='_blank' href='$completeurl'>$completeurl</a></br>";

		$request = curl_build($completeurl);

		$result2 = json_decode($request,true);
		$pageId2 = $result2[query][pageids][0];//get page id from article info
		$result22 = $result2[query][pages][$pageId2];//get actual article text
		$titleP2 = $result22[title];

		$result32 = $result22[revisions][0]['*'];
		$results42 = explode('{{', $result32);
		$results42 = str_ireplace('}}', '', $results42);

		$infoBox2 = preg_grep('/(?i)Infobox/', $results42);

	}

	//find items
	$imageArray = preg_grep('/image/',$infoBoxA);
	$authorArray = preg_grep('/author =/',$infoBoxA);
	$publisherArray = preg_grep('/publisher/',$infoBoxA);
	$isbnArray = preg_grep('/isbn/', $infoBoxA);
	$pubYearA = preg_grep('/pub_date/', $infoBoxA);
	$pubYearB = preg_grep('/published/', $infoBoxA);
	$languageArray = preg_grep('/language/', $infoBoxA);
	$releaseArray = preg_grep('/release_date/', $infoBoxA);
	
	//find new items
	if (is_array($infoBox2)&&count($infoBox2)>0)
	{
		$infoBox2 = array_values($infoBox2);//reindex
		$infoBox2 = $infoBox2[0];
		$infoBox2A[] = $infoBox2;//create array
		$infoBox2A = preg_replace('/\s\s+/', ' ', $infoBox2A);//replace multiple spaces with one
		$imageArray2 = preg_grep('/image/',$infoBox2A);
		$authorArray2 = preg_grep('/author.=/',$infoBox2A);
		$authorArray3 = preg_grep('/author/',$infoBox2A);
		$publisherArray2 = preg_grep('/publisher/',$infoBox2A);
		$isbnArray2 = preg_grep('/isbn/', $infoBox2A);
		$pubYearC = preg_grep('/pub_date/', $infoBox2A);
		$pubYearD = preg_grep('/published/', $infoBox2A);
		$languageArray2 = preg_grep('/language/', $infoBox2A);
		$releaseArray2 = preg_grep('/release_date/', $infoBox2A);
	}
	
	echo export_array($infoBoxA);
	echo export_array($infoBox2A);
	//echo export_array($authorArray3);
	//print_r($authorArray2);
		
	//$authorLink = preg_grep('/authorlink/', $xml3);
		
	//extract authors
	if ((is_array($authorArray)&&count($authorArray)>0)||(is_array($authorArray2)&&count($authorArray2)>0))
	{
		$author = array_glue($authorArray,$authorArray2,'|','author =');
		$author = string_fix($author,'author');	
		
	}
	
	if (is_array($authorLink)&&count($authorLink)>0)
	{
		$authorLink = array_values($authorLink);
		$authorLink = $authorLink[0];
		$authorLink = explode('|', $authorLink);
		$authorLink = preg_grep('/authorlink/', $authorLink);

		foreach ($authorLink as $authors)
		{
			//remove everything before = and everything after (
			$authorPos = strpos($authors,'=');

			if ($authorPos>0)
			{
				$authors = substr($authors,$authorPos+1);
			}

			$authorPos = strpos($authors,'(');

			if ($authorPos>0)
			{
				$authors = substr($authors,0,$authorPos);
			}

			$authorsArray[] = $authors;

		}

	}

	//extract publication year
	if ((is_array($pubYearA)&&count($pubYearA)>0)||(is_array($pubYearC)&&count($pubYearC)>0))
	{
		$pubYear = array_glue($pubYearA,$pubYearC,'|','pub_date');
		$pubYear = string_fix($pubYear,'in literature');
		$pubYear = string_fix($pubYear,'pub_date');
		
		if (strlen($pubYear)>4)
		{
			$pubYear = date_fix($pubYear);//test if its a valid date
		}
	}
	else if ((is_array($pubYearB)&&count($pubYearB)>0)||(is_array($pubYearD)&&count($pubYearD)>0))
		{
			$pubYear = array_glue($pubYearB,$pubYearD,'|','published');
			$pubYear = string_fix($pubYear,'published');
			$pubYear = string_chop($pubYear,'(');
			
			if (strlen($pubYear)>4)
			{
				$pubYear = date_fix($pubYear);//test if its a valid date			
			}

		}
	//if the date isn't a year, unset it
	if (is_numeric($pubYear)===FALSE)
	{
		//echo "Unsetting year<br/>";
		unset($pubYear);
	}
		


	//search for a release date if there is no publication year
	if ((is_array($releaseArray)&&count($releaseArray)>0)||(is_array($releaseArray2)&&count($releaseArray2)>0)&&isset($pubYear)===FALSE)
	{
		$pubYear = array_glue($releaseArray,$releaseArray2,'|','release_date');
		$pubYear = string_fix($pubYear,'release_date');
		$pubYear = string_fix($pubYear,'in literature');
		$pubYear = string_chop($pubYear,'(');
		
		if (strlen($pubYear)>4)
		{
			
			$pubYear = date_fix($pubYear);//test if its a valid date	
		}
		
				
	}
		
	//parse title
	if (is_array($titleArray)&&count($titleArray)>0)
	{
		$titleArray = array_values($titleArray);//reindex
		$titleP = $titleArray[0];
		$titleP = string_fix($titleP,'title');
		$titleP = string_fix($titleP,'(disambiguation)');
	}
	else if (isset($titleP))
	{
		$titleP = string_fix($titleP,'(disambiguation)');
		
	}
	else if (isset($titleP2))
	{
		$titleP = string_fix($titleP2,'(disambiguation)');		
	}

	//parse publishers
	if ((is_array($publisherArray)&&count($publisherArray)>0)||(is_array($publisherArray2)&&count($publisherArray2)>0))
	{
		$pubP = array_glue($publisherArray,$publisherArray2,'|','publisher');
		//if there is both a UK and US publisher, remove the second one
		$pub2 = strpos($pubP, 'UK: [[');
		$pub3 = strpos($pubP, 'US: [[');
		if ($pub3>$pub2)//UK first
		{
		$pubP = substr($pubP, 0, $pub3-1);
		$pubP = str_ireplace('UK:', '', $pubP);
		}
		else if ($pub2>$pub3)//US first
		{
		$pubP = substr($pubP, 0, $pub2-1);
		$pubP = str_ireplace('US:', '', $pubP);
		}
		$pubP = string_fix($pubP,'publisher');
		$pubP = string_fix($pubP,'()');
		//if last character is a comma, remove it
		$pubP = rtrim($pubP, ',');
		$pubP = str_ireplace('(book )', '', $pubP);	

	}

	//parse language
	if((is_array($languageArray)&&count($languageArray)>0)||(is_array($languageArray2)&&count($languageArray2)>0))
	{
		$languageP = array_glue($languageArray,$languageArray2,'|','language');
		$languageP = string_fix($languageP,'language');
	}
	
	//parse ISBN
	if ((is_array($isbnArray)&&count($isbnArray)>0)||(is_array($isbnArray2)&&count($isbnArray2)>0))
	{
		//do we perform ISBN validation here or in the main page?
		$ISBNP = array_glue($isbnArray,$isbnArray2,'|','isbn');
		$ISBNP = string_fix($ISBNP,'isbn',0);//case insensitive search
		$ISBNP = str_ireplace('-', '', $ISBNP);//remove '-'
		$ISBNP = explode(' ',$ISBNP);//if there are multiple ISBNs, get the first one
		$ISBNP = $ISBNP[0];
		$ISBNP = preg_replace('/[^0-9xX]/', '', $ISBNP);//remove any non-digits
		//$ISBNP = preg_replace('/[^0-9].[^xX]*/', '', $ISBNP);
	}

	//parse Image
	if ((is_array($imageArray)&&count($imageArray)>0)||(is_array($imageArray2)&&count($imageArray2)>0))
	{
		$imageSearch = array_glue($imageArray,$imageArray2,'|','image');
		$imageSearch = string_fix($imageSearch,'image');
		$imageSearch = string_fix($imageSearch,'File:');
		$imageSearch = string_fix($imageSearch,'Image:');
		$imageSearch = string_fix($imageSearch,'<!--prefer 1st edition-->');
				
		$imageUrl = str_ireplace(' ','_',$imageSearch);
		//echo $imageUrl."<br/>";
		$imageUrl = 'http://en.wikipedia.org/w/api.php?action=query&titles=Image:'.$imageUrl.'&prop=imageinfo&iiprop=url&format=json&indexpageids&redirects&continue=';
		echo "<a href='$imageUrl'>$imageUrl</a></br></br>";

		$requestImg = curl_build($imageUrl);
		$resultImg = json_decode($requestImg,true);
		$imgPageId = $resultImg[query][pageids][0];
		$imgUrl = $resultImg[query][pages][$imgPageId][imageinfo][0][url];

	}

	if ($missing <> 1)//if page isn't missing
		{
		echo "<br/><br/>Wikipedia API values:<br/>";
		echo "Author(s): ".$author."<br/>";
		//print_r($authorsArray);
		echo "Year: ".$pubYear."<br/>";
		echo "Title: ".$titleP."<br/>";
		echo "Original language: ".$languageP."<br/>";
		echo "Publisher: ".$pubP."<br/>";
		echo "ISBN: ".$ISBNP."<br/>";
		echo "<img src=$imgUrl height=250><br/>";
	}
	else
	{
		echo "Page missing!";
	}
}
?>